// ignore_for_file: unused_import, avoid_print

import 'dart:async';
import 'dart:io';

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';

import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:tencent_calls_uikit/tencent_calls_uikit.dart';
import 'package:tencent_chat_i18n_tool/tencent_chat_i18n_tool.dart';

import 'package:tencent_cloud_chat_demo/config.dart';
import 'package:tencent_cloud_chat_demo/src/routes.dart';
import 'package:tencent_cloud_chat_demo/utils/toast.dart';
import 'package:tencent_cloud_chat_demo/utils/request.dart';
import 'package:tencent_cloud_chat_demo/utils/commonUtils.dart';
import 'package:tencent_cloud_chat_demo/src/provider/theme.dart';
import 'package:tencent_cloud_chat_demo/src/pages/home_page.dart';
import 'package:tencent_cloud_chat_demo/utils/GenerateTestUserSig.dart';
import 'package:tencent_cloud_chat_demo/src/pages/privacy/privacy_webview.dart';

import 'package:tencent_cloud_chat_uikit/theme/color.dart';
import 'package:tencent_cloud_chat_uikit/tencent_cloud_chat_uikit.dart';

import 'register_setting.dart';

class RegisterPage extends StatelessWidget {
  const RegisterPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final theme = Provider.of<DefaultThemeData>(context).theme;
    return WillPopScope(
        onWillPop: () async {
          return true;
        },
        child: Scaffold(
          appBar: AppBar(
            iconTheme: const IconThemeData(
              color: Colors.white,
            ),
            shadowColor: theme.weakDividerColor,
            elevation: 1,
            title: Text(
              TIM_t("注册"),
              style: const TextStyle(
                color: Colors.white,
                fontSize: 17,
              ),
            ),
            flexibleSpace: Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [
                    theme.lightPrimaryColor ?? CommonColor.lightPrimaryColor,
                    theme.primaryColor ?? CommonColor.primaryColor
                  ],
                ),
              ),
            ),
          ),
          body: const AppLayout(),
          resizeToAvoidBottomInset: false,
        ));
  }
}

class AppLayout extends StatelessWidget {
  const AppLayout({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        SystemChannels.textInput.invokeMethod('TextInput.hide');
      },
      child: Container(
        color: Colors.white,
        child: const Stack(
          children: [
            RegisterForm(),
          ],
        ),
      ),
    );
  }
}

class RegisterForm extends StatefulWidget {
  const RegisterForm({Key? key}) : super(key: key);

  @override
  _RegisterFormState createState() => _RegisterFormState();
}

class _RegisterFormState extends State<RegisterForm> {
  final CoreServicesImpl coreInstance = TIMUIKitCore.getInstance();

  String account = '';
  String password = '';
  bool isPasswordVisible = false;

  final TextEditingController _accountController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();

  final TextEditingController _verificationCodeController =
      TextEditingController();

  String phoneVerify = '';
  bool isPhoneVerify = false;
  String phoneVerifyText = '获取验证码';
  int phoneSeconds = 60;
  Timer? _phoneTimer;
  String emailVerify = '';
  bool isEmailVerify = false;
  String emailVerifyText = '获取验证码';
  int emailSeconds = 60;
  Timer? _emailTimer;

  int registerType = 1; //  1: 手机号验证码注册, 2: 邮箱验证码注册

  @override
  initState() {
    super.initState();
  }

  @override
  void dispose() {
    _accountController.dispose();
    _passwordController.dispose();
    _verificationCodeController.dispose();
    _phoneTimer?.cancel();
    _emailTimer?.cancel();
    super.dispose();
  }

  TextSpan webViewLink(String title, String url) {
    return TextSpan(
      text: TIM_t(title),
      style: const TextStyle(
        color: Color.fromRGBO(0, 110, 253, 1),
      ),
      recognizer: TapGestureRecognizer()
        ..onTap = () {
          Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (context) =>
                      PrivacyDocument(title: title, url: url)));
        },
    );
  }

  /// 获取验证码
  Future<void> sendVerificationCode() async {
    if (registerType == 1) {
      if (account.isEmpty) {
        ToastUtils.toast(TIM_t("请输入手机号"));
        return;
      }
      if (!RegExp(r'^[1][3-9]\d{9}$').hasMatch(account)) {
        ToastUtils.toast(TIM_t("请输入有效的手机号"));
        return;
      }

      if (isPhoneVerify) {
        return;
      }

      try {
        appRequest(
          method: 'post',
          path: 'https://yunpengim.daboluo.pro/api/sms/send',
          data: {
            'mobile': account,
            'event': 'register',
          },
        ).then((res) {
          if (res.data?['code'] == 1) {
            ToastUtils.toast(TIM_t("验证码已发送，请注意查收"));
            _phoneTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
              if (phoneSeconds == 0) {
                _phoneTimer?.cancel();
                phoneSeconds = 60;
                setState(() {
                  isPhoneVerify = false;
                  phoneVerifyText = '获取验证码';
                });
              } else {
                setState(() {
                  phoneSeconds--;
                  isPhoneVerify = true;
                  phoneVerifyText = '$phoneSeconds s';
                });
              }
            });
          } else {
            ToastUtils.toast(TIM_t(res.data?['msg'] ?? '网络故障，请稍后重试'));
          }
        });
      } catch (e) {
        print("Error sending verification code: $e");
      }
    } else if (registerType == 2) {
      if (account.isEmpty) {
        ToastUtils.toast(TIM_t("请输入邮箱"));
        return;
      }

      if (!RegExp(r'^[^@]+@[^@]+\.[^@]+').hasMatch(account)) {
        ToastUtils.toast(TIM_t("请输入有效的邮箱地址"));
        return;
      }

      if (isEmailVerify) {
        return;
      }

      _emailTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
        if (emailSeconds == 0) {
          _emailTimer?.cancel();
          emailSeconds = 60;
          setState(() {
            isEmailVerify = false;
            emailVerifyText = '获取验证码';
          });
        } else {
          setState(() {
            emailSeconds--;
            isEmailVerify = true;
            emailVerifyText = '$emailSeconds s';
          });
        }
      });
    }
  }

  /// 验证手机验证码
  Future<void> checkVerificationCode() async {
    try {
      appRequest(
        method: 'post',
        path: 'https://yunpengim.daboluo.pro/api/sms/check',
        data: {
          'mobile': account,
          'event': 'register',
          'captcha': phoneVerify,
        },
      ).then((res) {
        if (res.data?['code'] == 1) {
          userNext();
        } else {
          ToastUtils.toast(TIM_t(res.data?['msg'] ?? '网络故障，请稍后重试'));
        }
      });
    } catch (e) {
      print("Error checking verification code: $e");
    }
  }

  directToLoginPage() {
    Routes().directToLoginPage();
  }

  userNext() async {
    if (registerType == 2 && account.trim() == '') {
      ToastUtils.toast(TIM_t("请输入邮箱"));
      return;
    }

    if (registerType == 2 &&
        !RegExp(r'^[^@]+@[^@]+\.[^@]+').hasMatch(account)) {
      ToastUtils.toast(TIM_t("请输入有效的邮箱地址"));
      return;
    }

    if (registerType == 1 && account.trim() == '') {
      ToastUtils.toast(TIM_t("请输入手机号"));
      return;
    }

    if (registerType == 1 && phoneVerify.trim() == '') {
      ToastUtils.toast(TIM_t("请输入手机验证码"));
      return;
    }

    if (password.trim() == '') {
      ToastUtils.toast(TIM_t("请输入密码"));
      return;
    }

    String key = IMDemoConfig.key;
    int sdkAppId = IMDemoConfig.sdkAppID;
    if (key == "" || sdkAppId == 0) {
      ToastUtils.toast(TIM_t("请在 config.dart 中输入 sdkAppID 和 key"));
      return;
    }

    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => RegisterSetting(
          password: password,
          phone: registerType == 1 ? account : '',
          email: registerType == 2 ? account : '',
          captcha: phoneVerify,
        ),
      ),
    );
  }

  String? _errorText() {
    if (registerType == 2 && account.isNotEmpty) {
      return !RegExp(r'^[^@]+@[^@]+\.[^@]+').hasMatch(account)
          ? TIM_t("请输入有效的邮箱地址")
          : null;
    }
    if (registerType == 1 && account.isEmpty) {
      TIM_t("请输入手机号");
    }

    return null;
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(
      context,
      designSize: const Size(750, 1624),
      minTextAdapt: true,
    );
    return Stack(
      children: [
        Positioned(
          top: CommonUtils.adaptHeight(80),
          left: 0,
          right: 0,
          child: Center(
            child: SizedBox(
              height: CommonUtils.adaptHeight(200),
              child: Image.asset(
                "assets/logo.png",
                fit: BoxFit.contain,
              ),
            ),
          ),
        ),
        Positioned(
          bottom: CommonUtils.adaptHeight(120),
          child: Container(
            padding: const EdgeInsets.fromLTRB(40, 40, 40, 0),
            height: MediaQuery.of(context).size.height -
                CommonUtils.adaptHeight(600),
            width: MediaQuery.of(context).size.width,
            child: Form(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  TextField(
                    controller: _accountController,
                    autofocus: false,
                    decoration: InputDecoration(
                      contentPadding:
                          EdgeInsets.only(left: CommonUtils.adaptWidth(14)),
                      hintText: TIM_t(registerType == 1 ? '请输入手机号' : '请输入邮箱'),
                      hintStyle: TextStyle(
                        fontSize: CommonUtils.adaptFontSize(24),
                        color: Colors.grey,
                      ),
                      prefixIcon: Icon(
                          registerType == 1 ? Icons.phone : Icons.email,
                          color: Colors.grey),
                      suffixIcon: account.isNotEmpty
                          ? IconButton(
                              icon: const Icon(Icons.clear, color: Colors.grey),
                              onPressed: () {
                                setState(() {
                                  account = '';
                                  _accountController.clear();
                                });
                              },
                            )
                          : null,
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(8.0),
                        borderSide: const BorderSide(color: Colors.grey),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(8.0),
                        borderSide: const BorderSide(color: Colors.black),
                      ),
                      errorText: _errorText(),
                    ),
                    onChanged: (v) {
                      setState(() {
                        account = v;
                      });
                    },
                  ),
                  SizedBox(height: CommonUtils.adaptHeight(34)),
                  TextField(
                    controller: _verificationCodeController,
                    autofocus: false,
                    decoration: InputDecoration(
                      contentPadding: EdgeInsets.only(
                        left: CommonUtils.adaptWidth(14),
                      ),
                      hintText: TIM_t("请输入验证码"),
                      hintStyle: TextStyle(
                        fontSize: CommonUtils.adaptFontSize(24),
                        color: Colors.grey,
                      ),
                      prefixIcon: const Icon(
                        Icons.lock,
                        color: Colors.grey,
                      ),
                      suffixIcon: TextButton(
                        onPressed: () {
                          sendVerificationCode();
                        },
                        child: Text(
                          registerType == 1 ? phoneVerifyText : emailVerifyText,
                          style: TextStyle(
                            color: Colors.black,
                            fontSize: CommonUtils.adaptFontSize(24),
                          ),
                        ),
                      ),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(8.0),
                        borderSide: const BorderSide(color: Colors.grey),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(8.0),
                        borderSide: const BorderSide(color: Colors.black),
                      ),
                    ),
                    keyboardType: TextInputType.number,
                    onChanged: (v) {
                      setState(() {
                        registerType == 1 ? phoneVerify = v : emailVerify = v;
                      });
                    },
                  ),
                  SizedBox(height: CommonUtils.adaptHeight(34)),
                  TextField(
                    autofocus: false,
                    obscureText: !isPasswordVisible,
                    decoration: InputDecoration(
                      contentPadding:
                          EdgeInsets.only(left: CommonUtils.adaptWidth(14)),
                      hintText: TIM_t("请设置登录密码"),
                      hintStyle: TextStyle(
                        fontSize: CommonUtils.adaptFontSize(24),
                        color: Colors.grey,
                      ),
                      prefixIcon: const Icon(Icons.lock, color: Colors.grey),
                      suffixIcon: IconButton(
                        icon: Icon(
                          isPasswordVisible
                              ? Icons.visibility
                              : Icons.visibility_off,
                          color: Colors.grey,
                        ),
                        onPressed: () {
                          setState(() {
                            isPasswordVisible = !isPasswordVisible;
                          });
                        },
                      ),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(8.0),
                        borderSide: const BorderSide(color: Colors.grey),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(8.0),
                        borderSide: const BorderSide(color: Colors.black),
                      ),
                    ),
                    keyboardType: TextInputType.text,
                    onChanged: (v) {
                      setState(() {
                        password = v;
                      });
                    },
                  ),
                  Container(
                    margin: EdgeInsets.only(
                      top: CommonUtils.adaptHeight(200),
                    ),
                    child: Row(
                      children: [
                        Expanded(
                          child: ElevatedButton(
                            child: Text(TIM_t("下一步"),
                                style: const TextStyle(
                                  color: Colors.white,
                                )),
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Colors.black,
                            ),
                            onPressed: checkVerificationCode,
                          ),
                        )
                      ],
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(
                      top: CommonUtils.adaptHeight(100),
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        GestureDetector(
                          onTap: () {
                            setState(() {
                              registerType = 1;
                              account = '';
                              password = '';
                              _accountController.clear();
                              _passwordController.clear();
                              _verificationCodeController.clear();
                            });
                          },
                          child: Column(
                            children: [
                              Icon(
                                Icons.phone,
                                color: registerType == 1
                                    ? Colors.black
                                    : Colors.grey,
                                size: 40,
                              ),
                              Text(
                                TIM_t("手机号注册"),
                                style: TextStyle(
                                  color: registerType == 1
                                      ? Colors.black
                                      : Colors.grey,
                                  fontSize: CommonUtils.adaptFontSize(24),
                                ),
                              ),
                            ],
                          ),
                        ),
                        SizedBox(width: CommonUtils.adaptWidth(100)),
                        GestureDetector(
                          onTap: () {
                            setState(() {
                              registerType = 2;
                              account = '';
                              password = '';
                              _accountController.clear();
                              _passwordController.clear();
                              _verificationCodeController.clear();
                            });
                          },
                          child: Column(
                            children: [
                              Icon(
                                Icons.email,
                                color: registerType == 2
                                    ? Colors.black
                                    : Colors.grey,
                                size: 40,
                              ),
                              Text(
                                TIM_t("邮箱注册"),
                                style: TextStyle(
                                  color: registerType == 2
                                      ? Colors.black
                                      : Colors.grey,
                                  fontSize: CommonUtils.adaptFontSize(24),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
        )
      ],
    );
  }
}
